package com.example.safelib.fragment


import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.baselib.activity.ChooseNickActivity
import com.example.baselib.constants.MyConstants
import com.example.baselib.fragment.BaseFragment
import com.example.baselib.utils.TimeUtils

import com.example.safelib.R
import com.example.safelib.SafeViewModel
import com.example.safelib.adapter.SafeAlarmAdapter
import com.example.safelib.bean.SafeAlarmBean
import kotlinx.android.synthetic.main.fragment_safe_alarm.*
import java.lang.Exception
import java.util.*


/**
 * A simple [Fragment] subclass.
 */
class SafeAlarmFragment : BaseFragment<SafeViewModel>() {
    private lateinit var safeAlarmAdapter: SafeAlarmAdapter
    private lateinit var timer: Timer
    private lateinit var empty:View
    private val finish=777
    override fun providerVMClass(): Class<SafeViewModel>? {
        return SafeViewModel::class.java
    }

    override fun contentLayout(): Int {
       return R.layout.fragment_safe_alarm
    }

    override fun initView() {
        safeAlarmAdapter =SafeAlarmAdapter(R.layout.safe_alarm_item)
         empty = LayoutInflater.from(context).inflate(R.layout.empty_item, null, false)
        safeAlarmAdapter.emptyView=empty
        safe_alarm_srl.setColorSchemeColors(resources.getColor(R.color.colorDBlue))
        safe_alarm_srl.setOnRefreshListener {
            viewModel.isLoad=false
            viewModel.loadAlarmData()
        }
        safeAlarmAdapter.setOnItemClickListener { adapter, view, position ->
            val bundle = Bundle()
            val alarmBean = adapter.getItem(position) as SafeAlarmBean
            val startTime:String = TimeUtils.timeFormat(alarmBean.starttime)?: ""
            val endTime:String = TimeUtils.timeFormat(alarmBean.endtime )?: ""
            bundle.putString("sensornum",alarmBean.sensornum?:"")
            bundle.putString("starttime",startTime)
            bundle.putString("endtime",endTime)
            Navigation.findNavController(view).navigate(R.id.action_menu_safe_alarm_to_safeAlarmLCFragment,bundle)
        }
        safeAlarmAdapter.setOnItemChildClickListener { adapter, _, position ->
            val moreLy: LinearLayout = adapter.getViewByPosition(position, R.id.safe_alarm_more_ly) as LinearLayout
            val moreSh: ImageView = adapter.getViewByPosition(position, R.id.safe_alarm_sh) as ImageView
            if (moreLy?.isVisible) {
                moreLy.visibility = View.GONE
                moreSh.setImageResource(R.mipmap.expand)
            } else {
                moreLy.visibility = View.VISIBLE
                moreSh.setImageResource(R.mipmap.fold)
            }
        }
        safe_alarm_rcy.adapter=safeAlarmAdapter
        safeAlarmAdapter.bindToRecyclerView(safe_alarm_rcy)
        safe_alarm_rcy.layoutManager =  LinearLayoutManager(activity, LinearLayoutManager.VERTICAL,false)

        safe_alarm_nickname.setOnClickListener {
            if (MyConstants.userData.usertype>1){
                startActivityForResult(Intent(activity,ChooseNickActivity::class.java),finish)
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        super.onActivityResult(requestCode, resultCode, intent)
        if (resultCode==0&&requestCode==finish){
            val map:HashMap<String,String> =HashMap()
            if (intent != null) {
                map["unitname"]= intent.getStringExtra("unitname")
                map["unitcode"]=intent.getStringExtra("unitcode")
                viewModel.setUnitInfo(map)
                viewModel.loadAlarmData()
                safe_alarm_nickname.text=map["unitname"]

            }

        }
    }
    override fun initData() {
        if (!viewModel.getUnitInfo().isNullOrEmpty()){
            safe_alarm_nickname.text=viewModel.getUnitInfo()["unitname"]
        }
        else if(!viewModel.getUserData().unitinfo.isNullOrEmpty()&&viewModel.getUserData().usertype==1){
            val map:HashMap<String,String> =HashMap()
            map["unitname"]=viewModel.getUserData().unitinfo[0].nickname
            map["unitcode"]=viewModel.getUserData().unitinfo[0].unitcode
            viewModel.setUnitInfo(map)
            safe_alarm_nickname.text=viewModel.getUnitInfo()["unitname"]
        }else {
            empty.findViewById<TextView>(R.id.empty_msg).text="无煤矿信息"
            return
        }

        viewModel.getAlarmData().observe(this, Observer {
            safe_alarm_count.text="报警数：${it.size}"
            safeAlarmAdapter.setNewData(it)
            Log.i("alarm",it[0].starttime)
            safe_alarm_empty.visibility=View.INVISIBLE
        })

    }

    override fun onStart() {
        super.onStart()
        statTimer()
    }

    private fun statTimer(){
        timer=Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() {
                activity?.runOnUiThread {safe_alarm_srl?.isRefreshing=true}
                viewModel.isLoad=false
                viewModel.loadAlarmData()
            }
        }, 30000, 30000)
    }

    override fun requestFinally(it: Int?) {
        super.requestFinally(it)
        safe_alarm_srl.isRefreshing=false
    }

    override fun requestError(it: Exception?) {
        safe_alarm_empty.visibility=View.VISIBLE
        if (it?.message=="暂无数据"){
            safe_alarm_empty.findViewById<TextView>(R.id.err_txt).text=it?.message
            safe_alarm_empty.findViewById<TextView>(R.id.err_msg).visibility=View.INVISIBLE
//            safe_alarm_empty.findViewById<ImageView>(R.id.err_img).visibility=View.INVISIBLE
        }else{
            safe_alarm_empty.findViewById<TextView>(R.id.err_msg).text=it?.message
            super.requestError(it)
        }
        safe_alarm_empty.findViewById<Button>(R.id.err_rest_btn).setOnClickListener {  viewModel.loadAlarmData() }


    }

    override fun onStop() {
        super.onStop()
        timer?.cancel()
    }
}
